package com.tengju.bff.interfaces.shared;

import com.idanchuang.component.logback.util.LogUtil;
import com.idanchuang.support.mybatis.crypt.util.CryptUtil;
import org.apache.commons.lang3.StringUtils;

/**
 * 脱敏，加密
 *
 * @author 大木
 * @date: 2021/12/17 10:06 上午
 */
public class MaskCypherUtil {

    /**
     * 脱敏
     *
     * @param type   脱敏字段类型 1-手机号 2-姓名
     * @param source 源数据
     * @return {@link String}
     */
    public static String mask(String source, MaskType type) {
        int length = source.length();
        int mid = length / 2;
        if (StringUtils.isBlank(source) || null == type) {
            return "";
        }
        String result = "";
        switch (type) {
            case MOBILE:
                result = LogUtil.maskMobile(source);
                break;
            case ID_CARD_NAME:
                // eg: (王大妈) -> 王**  ; (慕容云海) -> 慕**海
                result = hideString(source, Math.min(mid, 1), mid / 2);
                break;
            case ID_CARD_NO:
                result = LogUtil.maskIdCard(source);
                break;
            case SOCIALLY_UNIFIED_CODE:
                // eg: *********0092
                result = hideString(source, 0, 4);
                break;
            case BANK_CARD_NO:
                // 展示固定格式：12个* + 卡号后四位
                result = "************" + StringUtils.substring(source, source.length() - 4);
                break;
            case ACCOUNT_NAME:
                result = hideString(source, Math.min(mid / 2, 4), Math.min(mid, 4));
                break;
            default:
        }
        return result;
    }

    /**
     * 加密
     *
     * @param source 源数据
     * @return {@link String}
     */
    public static String encrypt(String source) {
        if (StringUtils.isEmpty(source)) {
            return null;
        } else {
            return CryptUtil.encrypt(source);
        }
    }


    /**
     * 字符串脱敏
     *
     * @param startRetainLen 开头要保留长度
     * @param endRetainLen   结尾要保留长度
     * @return {@link String}
     */
    private static String hideString(String source, int startRetainLen, int endRetainLen) {
        char replaceChar = '*';
        String replaceStr = StringUtils.substring(source, startRetainLen, source.length() - endRetainLen);
        return StringUtils.replaceOnce(source, replaceStr, String.valueOf(replaceChar).repeat(replaceStr.length()));
    }

}
